#pragma once

#include <string>
#include <sstream>
#include <vector>
#include <iomanip>

namespace viml {

// JSON编码工具类
class JSONEncoder {
public:
    // 转义JSON字符串
    static std::string escape_string(const std::string& str) {
        std::ostringstream escaped;
        for (char c : str) {
            switch (c) {
                case '"': escaped << "\\\""; break;
                case '\\': escaped << "\\\\"; break;
                case '\b': escaped << "\\b"; break;
                case '\f': escaped << "\\f"; break;
                case '\n': escaped << "\\n"; break;
                case '\r': escaped << "\\r"; break;
                case '\t': escaped << "\\t"; break;
                default:
                    if (c >= 0 && c < 32) {
                        escaped << "\\u" << std::hex << std::setfill('0') << std::setw(4) << static_cast<int>(c);
                    } else {
                        escaped << c;
                    }
                    break;
            }
        }
        return escaped.str();
    }
    
    // 创建JSON对象
    static std::string object(const std::vector<std::pair<std::string, std::string>>& fields) {
        std::ostringstream json;
        json << "{";
        for (size_t i = 0; i < fields.size(); ++i) {
            if (i > 0) json << ",";
            json << "\"" << fields[i].first << "\":" << fields[i].second;
        }
        json << "}";
        return json.str();
    }
    
    // 创建JSON数组
    static std::string array(const std::vector<std::string>& elements) {
        std::ostringstream json;
        json << "[";
        for (size_t i = 0; i < elements.size(); ++i) {
            if (i > 0) json << ",";
            json << elements[i];
        }
        json << "]";
        return json.str();
    }
    
    // 创建JSON字符串值
    static std::string string_value(const std::string& str) {
        return "\"" + escape_string(str) + "\"";
    }
    
    // 创建JSON数字值
    static std::string number_value(double num) {
        return std::to_string(num);
    }
    
    // 创建JSON布尔值
    static std::string bool_value(bool b) {
        return b ? "true" : "false";
    }
    
    // 创建JSON null值
    static std::string null_value() {
        return "null";
    }
};

} // namespace viml